import JSEncrypt from '@/utils/jsencrypt.js'

const KEY_SIZE = 1024 // 使用1024位密钥

export class RSAUtil {
  constructor() {
    this.privateKey = ''
    this.publicKey = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCqYDnNgGpi8s5FR3d9ASco08WZFd5HNE+oAYFgr5nFRNPScV0DqXLU9oM+eeW0cyRmnh+WfrCUL2cUopwns4wv0O9lM93Ljaiskfjrwrrred7G82AAt6UfQNmheOcrQrKLU8znzDQ3N8cO6cD1CbuWgKB2JlndxotJFhO5OK4avwIDAQAB'
    this.encryptor = new JSEncrypt();
    this.decryptor = new JSEncrypt();
  }

  // 生成密钥对
  generateKeys() {
    const crypt = new JSEncrypt({ default_key_size: KEY_SIZE })
    crypt.getKey()
    this.privateKey = crypt.getPrivateKey()
    this.publicKey = crypt.getPublicKey()
  }

  // 通用加密方法
  encrypt(data, key) {
    const crypt = new JSEncrypt()
    crypt.setKey(key)
    return crypt.encrypt(data)
  }

  // 通用解密方法
  decrypt(encrypted, key) {
    const crypt = new JSEncrypt()
    crypt.setKey(key)
    return crypt.decrypt(encrypted)
  }

  // 使用公钥加密
  publicEncrypt(data) {
    return this.encryptLong(data, this.publicKey)
  }

  // 使用私钥解密
  privateDecrypt(encrypted) {
    return this.decryptLong(encrypted, this.privateKey)
  }

  // 使用私钥加密
  privateEncrypt(data) {
    return this.encryptLong(data, this.privateKey)
  }

  // 使用公钥解密
  publicDecrypt(encrypted) {
    return this.decryptLong(encrypted, this.publicKey)
  }

  // 修改分段加密方法（适配117字节分块）
  encryptLong(text, key) {
    this.encryptor.setPrivateKey(key);
    let result = this.encryptor.encryptByPrivate(text);
    return result;
  }
  
  // 修改分段解密方法（适配128字节分块）
  decryptLong(encryptedStr, key) {
    // 设置公钥
    this.decryptor.setPublicKey(key);
    let result = this.decryptor.decryptByPublic(encryptedStr);
    return result;
  }
  
  
}


// 示例用法：
/*
const rsa = new RSAUtil()
rsa.generateKeys()

const plainText = 'secret data'

// 公钥加密 -> 私钥解密
const encrypted1 = rsa.publicEncrypt(plainText)
const decrypted1 = rsa.privateDecrypt(encrypted1)

// 私钥加密 -> 公钥解密
const encrypted2 = rsa.privateEncrypt(plainText)
const decrypted2 = rsa.publicDecrypt(encrypted2)
*/